<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\JsonResponse;

class OrderController extends Controller
{
    /**
     * 显示订单管理页面
     */
    public function index(Request $request): View
    {
        $perPage = 20;
        $query = Order::with(['user', 'room']);

        // 搜索功能
        if ($request->filled('search')) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('id', 'like', "%{$search}%")
                  ->orWhereHas('user', function ($userQuery) use ($search) {
                      $userQuery->where('nickname', 'like', "%{$search}%")
                               ->orWhere('phone', 'like', "%{$search}%");
                  });
            });
        }

        // 状态筛选
        if ($request->filled('status')) {
            $status = $request->get('status');
            $query->where('status', $status);
        }

        // 日期筛选
        if ($request->filled('date')) {
            $date = $request->get('date');
            $query->whereDate('created_at', $date);
        }

        // 获取订单并计算统计数据
        $orders = $query->orderBy('created_at', 'desc')->paginate($perPage);
        
        // 为每个订单添加统计数据
        $orders->getCollection()->transform(function ($order) {
            // 计算菜品数量和总数量
            $orderDishes = $order->dishes ?? [];
            $order->dish_count = count($orderDishes);
            $order->total_quantity = array_sum(array_column($orderDishes, 'quantity'));
            return $order;
        });

        return view('admin.orders.index', compact('orders'));
    }

    /**
     * 显示订单详情页面
     */
    public function show(int $id): View
    {
        $order = Order::with(['user', 'room'])->findOrFail($id);
        
        // 解析订单项目
        $orderDishes = $order->dishes ?? [];
        $order->dish_count = count($orderDishes);
        $order->total_quantity = array_sum(array_column($orderDishes, 'quantity'));
        
        return view('admin.orders.show', compact('order', 'orderDishes'));
    }

    /**
     * 确认订单
     */
    public function confirm(int $id): RedirectResponse
    {
        $order = Order::findOrFail($id);
        $order->status = 'confirmed';
        $order->save();

        return redirect()->back()->with('success', "订单 #{$order->id} 已确认");
    }

    /**
     * 取消订单
     */
    public function cancel(int $id): RedirectResponse
    {
        $order = Order::findOrFail($id);
        $order->status = 'cancelled';
        $order->save();

        return redirect()->back()->with('success', "订单 #{$order->id} 已取消");
    }

    /**
     * 更新订单状态
     */
    public function updateStatus(Request $request, int $id): RedirectResponse
    {
        $request->validate([
            'status' => 'required|in:pending,confirmed,preparing,ready,delivered,cancelled'
        ]);

        $order = Order::findOrFail($id);
        $oldStatus = $order->status;
        $order->status = $request->status;
        
        // 如果状态变为已送达，记录送达时间
        if ($request->status === 'delivered' && !$order->delivery_time) {
            $order->delivery_time = now();
        }
        
        $order->save();

        $statusMap = [
            'pending' => '待处理',
            'confirmed' => '已确认',
            'preparing' => '制作中',
            'ready' => '已就绪',
            'delivered' => '已送达',
            'cancelled' => '已取消'
        ];

        $newStatusText = $statusMap[$request->status] ?? $request->status;
        return redirect()->back()->with('success', "订单 #{$order->id} 状态已更新为：{$newStatusText}");
    }

    /**
     * 获取订单列表API
     */
    public function list(Request $request): JsonResponse
    {
        $perPage = $request->get('per_page', 20);
        $query = Order::with(['user', 'room']);

        // 搜索功能
        if ($request->filled('search')) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('id', 'like', "%{$search}%")
                  ->orWhereHas('user', function ($userQuery) use ($search) {
                      $userQuery->where('nickname', 'like', "%{$search}%")
                               ->orWhere('phone', 'like', "%{$search}%");
                  });
            });
        }

        // 状态筛选
        if ($request->filled('status')) {
            $status = $request->get('status');
            $query->where('status', $status);
        }

        // 日期筛选
        if ($request->filled('date')) {
            $date = $request->get('date');
            $query->whereDate('created_at', $date);
        }

        $orders = $query->orderBy('created_at', 'desc')->paginate($perPage);
        
        // 为每个订单添加统计数据
        $orders->getCollection()->transform(function ($order) {
            $orderItems = json_decode($order->items, true) ?? [];
            $order->dish_count = count($orderItems);
            $order->total_quantity = array_sum(array_column($orderItems, 'quantity'));
            return $order;
        });

        return response()->json([
            'data' => $orders->items(),
            'pagination' => [
                'current_page' => $orders->currentPage(),
                'last_page' => $orders->lastPage(),
                'per_page' => $orders->perPage(),
                'total' => $orders->total(),
            ]
        ]);
    }

    /**
     * 获取订单详情API
     */
    public function showApi(int $id): JsonResponse
    {
        $order = Order::with(['user', 'room'])->findOrFail($id);
        
        // 解析订单项目
        $orderItems = $order->items ? json_decode($order->items, true) ?? [] : [];
        $order->dish_count = count($orderItems);
        $order->total_quantity = array_sum(array_column($orderItems, 'quantity'));
        
        return response()->json(['data' => $order]);
    }

    /**
     * 获取订单统计API
     */
    public function stats(): JsonResponse
    {
        $stats = [
            'total_orders' => Order::count(),
            'pending_orders' => Order::where('status', 'pending')->count(),
            'confirmed_orders' => Order::where('status', 'confirmed')->count(),
            'cancelled_orders' => Order::where('status', 'cancelled')->count(),
            'completed_orders' => Order::where('status', 'completed')->count(),
            'today_orders' => Order::whereDate('created_at', today())->count(),
            'this_month_orders' => Order::whereMonth('created_at', now()->month)->count(),
        ];

        return response()->json(['data' => $stats]);
    }
}
